
import { _decorator, Component, Node, Sprite, BoxCollider2D, Color, Prefab, TiledMap, find, CCString, AudioSource, instantiate, Vec3, Vec2 } from 'cc';
import { eventTarget } from '../Globle';
import { People } from '../People';
const { ccclass, property } = _decorator;
 
@ccclass('AttackedToolRoom')
export class AttackedToolRoom extends Component {
    @property(CCString) house_name:string;
    @property(Prefab) tool_people:Prefab;
    private tileMap:TiledMap;
    private audioSource:AudioSource;
    private gameScene:Node;
    onLoad () {
        this.gameScene = find('GameScene');
        this.tileMap = find('GameScene/TiledMap').getComponent(TiledMap)
        this.audioSource = this.getComponent(AudioSource);
        this.audioSource.node.on(AudioSource.EventType.ENDED,this.soundEnd,this);
        eventTarget.on('destoryAttackedWall',this.onAttacked,this);
    }

    //被攻击
    private onAttacked(uuid:string) {
        if(uuid==this.node.uuid){
            this.audioSource.play();
            this.getComponent(Sprite).color = new Color(0,0,0,0);
            this.node.getComponent(BoxCollider2D).destroy();
            let obj = this.tileMap.getObjectGroup(this.house_name);
            let line = obj.getObject('line');
            let people = instantiate(this.tool_people);
            let peopleScript = people.getComponent(People);
            let path = line.polylinePoints.map(v=>{
                return new Vec2(line.offset.x+v.x,-line.offset.y+v.y);
            })
            peopleScript.init(path);
            people.position = new Vec3(line.offset.x,-line.offset.y);
            this.gameScene.addChild(people);
        }
    }

    private soundEnd() {
        this.node.destroy();
    }
}
